package com.hys.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
public class DownLoadController {

    @RequestMapping("/download/{fileName:.+}")
    public ResponseEntity downLoad(@PathVariable String fileName, HttpSession session) throws IOException {
        String realPath = session.getServletContext().getRealPath("/download/" + fileName);

        FileInputStream fileInputStream = new FileInputStream(realPath);
        byte[] body = new byte[fileInputStream.available()];     //创建一个字节数组，  现在是空的
        fileInputStream.read(body);   //文件已经读到了字节数组中   现在不为空

        //设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        fileName = URLEncoder.encode(fileName,"utf-8");
        httpHeaders.add("Content-Disposition","attachment;filename="+fileName);

        /*写给浏览器 */
        //状态码   当时响应的内容
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body,httpHeaders, HttpStatus.OK);
        return responseEntity;

    }

}
